<?php

namespace App\Http\Controllers\Api\Wap;

use App\Http\Controllers\Common\ApiController;
use App\Models\Article\ArticleOrder;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use App\Models\User\CallbackPayLog;
use App\Models\User\MemberOrder;
use App\Models\User\User;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\OfficialAccount\Material\Client;

class WxController extends ApiController {

    protected function handleEvent($message){
        $str="";
        //Log::info('handleEvent',$message);
        $open_id = $message['FromUserName'];
        switch ($message['Event']){
            case 'subscribe':
                $eventKey = $message['EventKey'];

                $eventKey = str_replace('qrscene_act1_', "", $eventKey);

                //Log::info('eventKey:'.$eventKey);
                $download = SysSetting::whereIn('key',['downloadPPT','downloadWord'])->pluck('val','key')->toArray();
                $info = ['open_id'=>$open_id,'download_ppt'=>$download['downloadPPT'],'download_word'=>$download['downloadWord']];
                //$user =  User::firstOrCreate(compact('open_id'),$info);

                //Cache::put($eventKey,$user->id,600);
                //Log::info('cache:',[Cache::get($eventKey)]);
                /*$str .= "您好！老铁欢迎关注“池塘边素材库”公众号!\n";
                $str .= '我们的网址:<a href="http://ctb.lyxinxiangyi.cn/">http://ctb.lyxinxiangyi.cn/</a>'."\n";
                $str .= "海量稿子素材，每日更新上千篇，紧跟工作节奏，满足您所需！\n";
                $str .= "更多功能等您来解锁哟~\n";
                $str .= "\n";
                $str .= "每天3毛钱，开通年费VIP，全站素材任意下载，从此远离加班熬夜！\n";*/

                $str = '您好！欢迎文友关注“池塘边素材”公众号!

海量稿子及PPT，每日更新百余篇，紧跟工作节奏，满足您所需！

<a href="https://ctbsc-wap.lyxinxiangyi.cn/" >→→点击[进入搜索]</a>

<a href="https://ctbsc-wap.lyxinxiangyi.cn/teach">→→点击[查看搜索教程]</a>

搜索技巧：可以2个或2个以上关键词进行搜索，中间加空格
ps：关键词+空格+关键词

没搜索到的加微信：ctbsc2021，私发关键词给客服即可快速获取！

网址：http://ctb.lyxinxiangyi.cn/

每天3毛钱，开通年费VIP，全站素材任意下载，从此远离加班熬夜！';
                break;
            case 'SCAN':
                $eventKey = $message['EventKey'];
                $eventKey = str_replace('act1_', "", $eventKey);

                $download = SysSetting::whereIn('key',['downloadPPT','downloadWord'])->pluck('val','key')->toArray();
                $info = ['open_id'=>$open_id,'download_ppt'=>$download['downloadPPT'],'download_word'=>$download['downloadWord']];
                //$user =  User::firstOrCreate(compact('open_id'),$info);
                //Cache::put($eventKey,$user->id,600);
                //Log::info('SCANcache:',[Cache::get($eventKey)]);
                break;
            case 'CLICK':

                $eventKey = $message['EventKey'];
                //Log::info('click,eventKey');
                if($eventKey=='qun'){
                    $config = config('wechat.default');
                    $app = Factory::officialAccount($config);
                    //$message = new Text('加客服微信，秒拉入群！');
                    $message = new Text('欢迎扫码入群！');
                    $app->customer_service->message($message)->to($open_id)->send();
                    $d = ['offset' => 0, 'count' => 10, 'type' => 'image'];
                    $c = new Client($app);
                    $res =  $c->httpPostJson('cgi-bin/material/batchget_material', $d);
                    $images = $res['item'];
                    $mediaId = '';
                    foreach ($images as $image) {
                        if(Str::contains($image['name'], 'kefu')){
                            $mediaId = $image['media_id'];
                            break;
                        }
                    }
                    $image = new Image($mediaId);
                    return $image;
                }elseif ($eventKey=='openid'){
                    $str = "您的ID为：$open_id";
                }else{
                    $str="您好！欢迎文友关注“池塘边素材”公众号!";
                }
                break;

        }

        return $str;
    }

    protected function handleText($message){

        $str="";
        $open_id = $message['FromUserName'];
        $content = $message['Content'];

        if(Str::contains($content, "客服") || Str::contains($content, "人呢")){
            $str = "客服微信:ctbsc2021";
        }
        elseif(Str::contains($content, "网址")){
            $str = "手机端网址：https://ctbsc-wap.lyxinxiangyi.cn/\nPC端网址：https://ctb.lyxinxiangyi.cn/";
        }else{
            $str = "搜索资料，请进入\n手机端网址：https://ctbsc-wap.lyxinxiangyi.cn/\nPC端网址：https://ctb.lyxinxiangyi.cn/";
        }

        return $str;
    }

    public function server(Request $request) {
        $config = config('wechat.default');

        $app = Factory::officialAccount($config);

        $app->server->push(function ($message) {
            //Log::info('server',$message);
            switch ($message['MsgType']) {
                case 'event':
                    return $this->handleEvent($message);
                    break;
                case 'text':
                    return $this->handleText($message);
                    break;
                default:
                    break;
            }
        });

        return $app->server->serve();
    }

    public function setMenu() {
        $config = config('wechat.default');
        $app = Factory::officialAccount($config);

        $buttons = [
            [
                "type" => "view",
                "name" => "搜资料",
                //"url"  => env('APP_URL').'/dist/#/file/login?p=index'
                "url"  => 'https://ctbsc-wap.lyxinxiangyi.cn/'
            ],
            [
                'name'=>'入免费群',
                'sub_button'=>[
                    [
                        "type" => "click",
                        "name" => "入免费群",
                        "key"  => "qun"
                    ],
                    [
                        "type" => "view",
                        "name" => "搜索教程1",
                        "url"  => "https://ctbsc-wap.lyxinxiangyi.cn/teach"
                    ],
                    [
                        "type" => "view",
                        "name" => "测试",
                        "key"  => "http://tep-wap.lyxinxiangyi.cn/login"
                    ],
                ]
            ],
            [
                "type" => "view",
                "name" => "升级会员",
                //"url"  => env('APP_URL').'/dist/#/file/login?p=myInfo'
                "url"  => 'https://ctbsc-wap.lyxinxiangyi.cn/vip'
            ],
        ];

        $app->menu->create($buttons);
        return responseSuccess([],0,'设置菜单成功');
    }

    public function saveCallbackPayLog($message,string $type='member'){
        try {
            $order_number = $message['out_trade_no'];
            $transaction_id = $message['transaction_id'];
            $res = json_encode($message,JSON_UNESCAPED_UNICODE);
            CallbackPayLog::create(compact('order_number','transaction_id','res','type'));
            return true;
        } catch (\Exception $e) {
           return true;
        }

    }

    public function payCallback(Request $request) {
        $config = config('wechat.default');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app){
            $isTestEnv = env('APP_ENV','test')=='test';
            $this->saveCallbackPayLog($message);
            $order_number = $message['out_trade_no'];
            $order = MemberOrder::where(compact('order_number'))->first();
            if(!empty($order) && $order->is_finished==2 && $order->is_auto==1){
                $user = User::where('id',$order->user_id)->first();
                if(!empty($user)){
                    $type = $order->type;
                    if($type=='first'){
                        $user->expire_time = Carbon::now()->addDays(30)->format('Y-m-d H:i:s');
                    }elseif ($type=='month'){
                        $user->expire_time = $user->is_member==1?Carbon::parse($user->expire_time)->addDays(30)->format('Y-m-d H:i:s'):
                            Carbon::now()->addDays(30)->format('Y-m-d H:i:s');
                    }elseif ($type=='quarter'){
                        $user->expire_time = $user->is_member==1?Carbon::parse($user->expire_time)->addDays(90)->format('Y-m-d H:i:s'):
                            Carbon::now()->addDays(90)->format('Y-m-d H:i:s');
                    }elseif ($type=='year'){
                        $user->expire_time = $user->is_member==1?Carbon::parse($user->expire_time)->addYears()->format('Y-m-d H:i:s'):
                            Carbon::now()->addYears()->format('Y-m-d H:i:s');
                    }else{
                        Log::error('未知的会员类型：'.$type);
                        return true;
                    }
                    $user->is_member = 1;
                    $user->type = $order->type;
                    $user->save();
                    $order->is_finished =1 ;
                    $order->save();
                }//empty user
            }elseif (!empty($order) && $order->is_finished==2 && $order->is_auto==3){
                $user = User::where('id',$order->user_id)->first();
                if(!empty($user)){
                    $type = $order->type;
                    if($type=='exfirst'){
                        $user->ex_expire_time = Carbon::now()->addDays(Constant::ExFirstDay)->format('Y-m-d H:i:s');
                    }elseif ($type=='exmonth'){
                        $user->ex_expire_time =  $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addDays(30)->format('Y-m-d H:i:s'):
                            Carbon::now()->addDays(30)->format('Y-m-d H:i:s');
                    }elseif ($type=='exquarter'){
                        $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addDays(90)->format('Y-m-d H:i:s'):
                            Carbon::now()->addDays(90)->format('Y-m-d H:i:s');
                    }elseif ($type=='exyear'){
                        $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addYear()->format('Y-m-d H:i:s'):
                            Carbon::now()->addYears()->format('Y-m-d H:i:s');
                    }else{
                        Log::error('未知的会员类型：'.$type);
                        return true;
                    }
                    $user->ex_is_member = 1;
                    $user->ex_type = $order->type;
                    $user->save();
                    $order->is_finished =1 ;
                    $order->save();
                }

            }else{

            }
            return true;
        });
        return $response;
    }

    public function payCallbackForArticle(Request $request) {
        //Log::info('进入支付回调了！');
        $config = config('wechat.default');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app){
            $this->saveCallbackPayLog($message,'article');
            $order_number = $message['out_trade_no'];
            $order = ArticleOrder::where(compact('order_number'))->first();
            if(!empty($order) && $order->is_finished==2){
                $order->is_finished =1 ;
                $order->save();
            }
            return true;
        });
        return $response;
    }


}
